import { reactive, computed, watch } from 'vue'
import type { PropertyPanelProps, GatewayConfig } from '../types'
import Modeling from 'bpmn-js/lib/features/modeling/Modeling.js'

export function useGatewayConfig(props: PropertyPanelProps) {
  const gatewayConfig = reactive<GatewayConfig>({
    defaultFlow: '',
  })

  const showGatewayConfig = computed(() => {
    const type = props.currentElement?.type || ''
    return ['bpmn:ExclusiveGateway', 'bpmn:InclusiveGateway'].includes(type)
  })

  const outgoingFlows = computed(() => {
    return props.currentElement?.outgoing || []
  })

  const handleGatewayChange = () => {
    if (!props.currentElement || !props.modeler) return

    const modeling = props.modeler.get('modeling') as Modeling
    const defaultFlow = outgoingFlows.value.find((flow) => flow.id === gatewayConfig.defaultFlow)

    if (defaultFlow) {
      modeling.updateProperties(props.currentElement, {
        default: defaultFlow.businessObject,
      })
    }
  }

  // 监听当前元素变化，更新配置
  watch(
    () => props.currentElement,
    (element) => {
      if (element && showGatewayConfig.value) {
        gatewayConfig.defaultFlow = element.businessObject.default?.id || ''
      } else {
        gatewayConfig.defaultFlow = ''
      }
    },
    { immediate: true },
  )

  return {
    gatewayConfig,
    showGatewayConfig,
    handleGatewayChange,
    outgoingFlows,
  }
}
